package com.suxin.netty.buf;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * @Classname NettyServerHandler
 * @Description [ 自定义一个 Handler ]
 * @Author Tang
 * @Date 2021/1/2 23:03
 * @Created by ASUS
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 实际数据读取
     * @param ctx 上下文对象，含有pipeline ，通道 channel,地址
     * @param msg 就是客户端发送的数据，默认是Object
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(Thread.currentThread().getName() + " server ctx = " + ctx);
        MyDataInfo.MyMessage myMessage = (MyDataInfo.MyMessage) msg;

        if (myMessage.getDataTypeValue() == 0) {
            MyDataInfo.Student student = myMessage.getStudent();
            System.out.println("客户端发送的消息：student, id =" + student.getId() + " name = " + student.getName());
        }

        if (myMessage.getDataTypeValue() == 1) {
            MyDataInfo.Worker worker = myMessage.getWorker();
            System.out.println("客户端发送的消息：worker, id =" + worker.getId() + " name = " + worker.getName());
        }

        System.out.println("客户端地址：" + ctx.channel().remoteAddress());
    }

    /**
     * 读取完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, client!喵喵3!", Charset.defaultCharset()));
    }

    /**
     * 处理异常，一般是关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}